package com.syg.logback.listener;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.LoggerContextListener;
import ch.qos.logback.core.Context;
import ch.qos.logback.core.spi.ContextAwareBase;
import ch.qos.logback.core.spi.LifeCycle;
import com.syg.boot.util.net.OsUtil;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 * @author syg
 * @version 1.0
 * @date 2021年11月24日19:14:46
 */
public class LoggerStartupListener extends ContextAwareBase implements LoggerContextListener, LifeCycle {
    org.slf4j.Logger log = LoggerFactory.getLogger(LoggerStartupListener.class);
    private boolean started = false;

    @Override
    public boolean isResetResistant() {
        return false;
    }

    @Override
    public void onStart(LoggerContext context) {

    }

    @Override
    public void onReset(LoggerContext context) {

    }

    @Override
    public void onStop(LoggerContext context) {

    }

    @Override
    public void onLevelChange(Logger logger, Level level) {

    }

    @Override
    public void start() {
        if (!this.started) {
            Context context = this.getContext();
            String path = this.getLogPath();
            context.putProperty("sygLogPath", path);
            this.makeTempDir();
            this.started = true;
        }
    }

    public String getLogPath() {
        boolean isWinOrMac = OsUtil.isWin() || OsUtil.isMac();
        String path = "/home/syg/app";
        if (isWinOrMac) {
            path = ".";
        }

        return path;
    }

    private void makeTempDir() {
        try {
            boolean isLinux = OsUtil.isLinux();
            if (isLinux) {
                File file = new File("/home/syg/app/temp");
                if (!file.exists()) {
                    file.mkdirs();
                }

                File uplodDir = new File("/home/syg/app/temp/upload");
                if (!uplodDir.exists()) {
                    uplodDir.mkdirs();
                }
            }
        } catch (Throwable e) {
            log.error("LoggerStartupListener makeTempDir exception", e);
        }

    }

    @Override
    public void stop() {

    }

    @Override
    public boolean isStarted() {
        return false;
    }
}
